package com.oigx.lookmu.core;


import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TxtReaderUtil {

    private final static String TITLE_MARK = "^第.*章.*$";

    public static String detectFileEncoding(String filePath) {
        try {
            com.ibm.icu.text.CharsetDetector detector = new com.ibm.icu.text.CharsetDetector();
            detector.setText(Files.readAllBytes(Paths.get(filePath)));
            com.ibm.icu.text.CharsetMatch match = detector.detect();
            return match.getName();
        } catch (Exception e) {
            e.printStackTrace();
            return StandardCharsets.UTF_8.name();
        }
    }


    public static List<TxtBook> loadBook(String filePath) {
        File file = new File(filePath);
        List<TxtBook> txtBookList = new ArrayList<>();
        if (file.exists() && file.isDirectory()){
            for (File subFile : Objects.requireNonNull(file.listFiles())){
                if (!subFile.isFile()){
                    continue;
                }
                String fileName = subFile.getName();
                if (!fileName.endsWith(".txt")){
                    continue;
                }
                System.out.println("bookName:" + fileName);
                String charsetName = detectFileEncoding(subFile.getAbsolutePath());

                TxtBook txtBook = new TxtBook(subFile.getAbsolutePath(), fileName, charsetName);
                txtBookList.add(txtBook);
            }
        }
        return txtBookList;
    }



    public static List<TxtChapter> readFile(String filePath, String charsetName) {
        List<TxtChapter> result = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath)), Charset.forName(charsetName)))) {
            String line;
            int currentLine = 0;
            while ((line = br.readLine()) != null) {
                if (line.trim().matches(TITLE_MARK)) {
                    TxtChapter txtChapter = new TxtChapter(line.trim(), currentLine, 0);
                    result.add(txtChapter);
                    if (result.size() != 1) {
                        result.get(result.size() - 2).setEndLine(result.get(result.size() - 1).getStartLine());
                    }
                }
                currentLine++;
            }
            if (result.size() != 0) {
                result.get(result.size() - 1).setEndLine(currentLine);
            } else {
                result.add(new TxtChapter("",0,currentLine));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }



    public static List<String> readChapter(String filePath, int startLine, int endLine, String charsetName, int maxChar) {
        Charset charset = StandardCharsets.UTF_8;
        if (charsetName!=null){
            charset = Charset.forName(charsetName);
        }
        List<String> result = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath)), charset))) {
            String line;
            int currentLine = 0;
            while ((line = br.readLine()) != null) {
                if (currentLine >= startLine && currentLine <= endLine && StringUtils.isNotBlank(line)) {
                    if (line.length()>maxChar){
                        System.out.println("line too long:"+line.length()+" max char:"+maxChar);
                        String l1 = line.substring(0,maxChar);
                        String l2 = line.substring(maxChar);
                        result.add(l1);
                        result.add(l2);
                    } else {
                        result.add(line);
                    }
                }
                currentLine++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }




}
